const router = require("koa-router")()

router.prefix("/admin")

const ServerUrl = require("../models/config").ServerUrl

var upload = require("../models/multer").upload

var unlink = require("../models/multer").unlink

const CtxBody = require("../models/config").CtxBody

const hotSearch = require("../models/HotSearch")

const Menu = require("../models/menu")

const Banner = require("../models/banner")

const { AdminUser, User } = require("../models/users")
// 后台添加热搜

router.post("/addHotSearch", async ctx => {
    let { name,status, type, id } = ctx.request.body 
    if (id) {
        let res = await hotSearch.findOneAndUpdate({ _id: id }, {
            $set: {
                name,
                type,
                status
            }
        })
        if (res) {
            CtxBody(ctx, 204, "")
        } else {
            CtxBody(ctx, 304, "")
        }
    } else {
        let res = await hotSearch.findOne({ name })
        if (res) {
            CtxBody(ctx, 402, "")
        } else {
            let newHot = new hotSearch({
                name,
                status,
                type,
            })
            let ret = await newHot.save()
            CtxBody(ctx, 202, "")
        }
    }
})

// 小程序后台热搜展示

router.post("/showHotSearch", async ctx => {
    let { page } = ctx.request.body
    let skipPage = page ? page : 1
    let PageSize = 10
    let AllConut = await hotSearch.find()
    let res = await hotSearch.find({ }, "_id name status addtime").skip(( skipPage - 1 ) * PageSize).limit(PageSize)
    if (res) {
        let newArr = []
            res.forEach( el => {
                let time = new Date(el.addtime).toLocaleString()
                newArr.push({
                    addtime: time,
                    id: el._id,
                    name:el.name,
                    status: el.status,
                    
                })
            })
            CtxBody(ctx, 200, {newArr, total:AllConut.length})
    } else {
        CtxBody(ctx, 404, "")
    }
})

// 小程序热搜状态改变

router.post("/changeHotSearchStatus", async ctx => {
    let { id } = ctx.request.body 
    let menu = await hotSearch.findOne({_id:id })
    // console.log(menu);
    
    let Menu_Status = menu.status
    if (Menu_Status == 1) {
        let edit = await hotSearch.findOneAndUpdate({ _id:id }, {
            $set: {
                status: "2"
            }
        }, { new: true })
        if (edit) {
            CtxBody(ctx, 204, "")
        } else {
            CtxBody(ctx, 304, "")
        }
    } else {
        let edit = await hotSearch.findOneAndUpdate({ _id:id }, {
            $set: {
                status: "1"
            }
        }, { new: true })
        if (edit) {
            CtxBody(ctx, 204, "")
        } else {
            CtxBody(ctx, 304, "")
        }
    }
})

//   小程序后台上传海报

router.post("/addBanner", upload.single("banner"), async ctx => {
    let filename = ctx.req.file.filename ? ctx.req.file.filename : " "
    let { link, id, status, type } = ctx.req.body
    if (id) {
            let img = await Banner.findOne({ _id: id })
            let oldfile = img.url.replace(`${ServerUrl}/public/uploads/`, "")
            let isOK = await unlink(oldfile)
            if (isOK == 1) {
                let update = await Banner.findOneAndUpdate({ _id: id } , {
                    $set: {
                        url: `${ServerUrl}/public/uploads/${filename}`,
                        link,
                        status,
                        type
                    }
                }, { new: true })
                if (update) {
                    CtxBody(ctx, 204, "")
                } else {
                    CtxBody(ctx, 304, "")
                }
            }
    } else {
 
        
        if (filename) {
            let res = new Banner({
                url: `${ServerUrl}/public/uploads/${filename}`,
                link,
                status,
                type
            })
            let ret = await res.save()
            if (ret) {
                CtxBody(ctx, 202, "")
            } else {
                CtxBody(ctx, 402, "")
            }
        } else {
            CtxBody(ctx, 404, "")
        }
    }
})

// 修改图片时不修改图片

router.post("/editBannerwithnoimg", async ctx => {
    console.log(ctx.request.body);
    
    let { link, id, status, type } = ctx.request.body
    let ban = await Banner.findOneAndUpdate({ _id: id }, {
        $set: {
            link,
            type,
            status
        }
    }, { new: true})
    if (ban) {
        CtxBody(ctx, 204, "")
    } else {
        CtxBody(ctx, 304, "")
    }
})

// 小程序海报状态改变

router.post("/changeBannerStatus", async ctx => {
    let { id } = ctx.request.body 
    let menu = await Banner.findOne({_id:id })
    // console.log(menu);
    
    let Menu_Status = menu.status
    if (Menu_Status == 1) {
        let edit = await Banner.findOneAndUpdate({ _id:id }, {
            $set: {
                status: "2"
            }
        }, { new: true })
        if (edit) {
            CtxBody(ctx, 204, "")
        } else {
            CtxBody(ctx, 304, "")
        }
    } else {
        let edit = await Banner.findOneAndUpdate({ _id:id }, {
            $set: {
                status: "1"
            }
        }, { new: true })
        if (edit) {
            CtxBody(ctx, 204, "")
        } else {
            CtxBody(ctx, 304, "")
        }
    }
})

// 小程序后台海报展示

router.post("/showBanner", async ctx => {
    let { type, page } = ctx.request.body 
    let skipPage = page ? page : 1
    let PageSize = 10
    let AllConut = await Banner.find()
    if (type) {
        let res = await Banner.find({ type }).skip(( skipPage - 1 ) * PageSize).limit(PageSize)
        
        if (res) {
            CtxBody(ctx, 200, {res, total: AllConut.length })
        } else {
            CtxBody(ctx, 404, "")
        }
    } else {
        let res = await Banner.find().skip(( skipPage - 1 ) * PageSize).limit(PageSize)

        if (res) {
            let newArr = []
            res.forEach( el => {
                let time = new Date(el.addtime).toLocaleString()
                newArr.push({
                    addtime: time,
                    id: el._id,
                    url: el.url,
                    link: el.link,
                    status: el.status,
                    type: el.type
                })
            })
            CtxBody(ctx, 200, {newArr, total: AllConut.length })
        } else {
            CtxBody(ctx, 404, "")
        }
    }
})



// 小程序菜单添加或修改

router.post("/addMenu", upload.single("menu"), async ctx => {
    let filename = ctx.req.file.filename
    let { link, id, status, name } = ctx.req.body
    if (id) {
        let img = await Menu.findOne({ _id: id })
        let oldfile = img.url.replace(`${ServerUrl}/public/uploads/`, "")
        let isOK = await unlink(oldfile)
        if (isOK == 1) {
            let update = await Menu.findOneAndUpdate({ _id: id } , {
                $set: {
                    url: `${ServerUrl}/public/uploads/${filename}`,
                    link,
                    status,
                    name
                }
            }, { new: true })
            if (update) {
                CtxBody(ctx, 204, "")
            } else {
                CtxBody(ctx, 304, "")
            }
        }
    } else {
        if (filename) {
            let res = new Menu({
                url: `${ServerUrl}/public/uploads/${filename}`,
                link,
                status,
                name
            })
            let ret = await res.save()
            if (ret) {
                CtxBody(ctx, 202, "")
            } else {
                CtxBody(ctx, 402, "")
            }
        } else {
            CtxBody(ctx, 404, "")
        }
    }
})

// 修改菜单时不修改图片

router.post("/editMenuwithnoimg", async ctx => {

    let { link, id, status, name } = ctx.request.body
    let ban = await Menu.findOneAndUpdate({ _id: id }, {
        $set: {
            link,
            name,
            status
        }
    }, { new: true})
    if (ban) {
        CtxBody(ctx, 204, "")
    } else {
        CtxBody(ctx, 304, "")
    }
})

// 小程序菜单状态改变

router.post("/changeMenuStatus", async ctx => {
    let { id } = ctx.request.body 
    let menu = await Menu.findOne({_id:id })
    let Menu_Status = menu.status
    if (Menu_Status == 1) {
        let edit = await Menu.findOneAndUpdate({ _id:id }, {
            $set: {
                status: "2"
            }
        }, { new: true })
        if (edit) {
            CtxBody(ctx, 204, "")
        } else {
            CtxBody(ctx, 304, "")
        }
    } else {
        let edit = await Menu.findOneAndUpdate({ _id:id }, {
            $set: {
                status: "1"
            }
        }, { new: true })
        if (edit) {
            CtxBody(ctx, 204, "")
        } else {
            CtxBody(ctx, 304, "")
        }
    }
})



// 小程序后台菜单展示

router.post("/showMenu", async ctx => {
    let { page } = ctx.request.body
    let skipPage = page ? page : 1
    let PageSize = 10
    let AllConut = await Banner.find()
    let res = await Menu.find().skip(( skipPage - 1 ) * PageSize).limit(PageSize)
    if (res) {
        let newArr = []
            res.forEach( el => {
                let time = new Date(el.addtime).toLocaleString()
                newArr.push({
                    addtime: time,
                    id: el._id,
                    url: el.url,
                    link: el.link,
                    status: el.status,
                    name: el.name
                })
            })
            // console.log(newArr);
            
        CtxBody(ctx, 200, {newArr, total:AllConut.length})
    } else {
        CtxBody(ctx, 404, "")
    }
})

// 小程序后台获取管理员列表

router.post("/getAllAdminUser", async ctx => {
    let { page } = ctx.request.body 
    let skipPage = page ? page : 1
    let PageSize = 10
    let user = await AdminUser.find().skip( (skipPage - 1) * PageSize ).limit( PageSize )
    let count = await AdminUser.count()
    if (user) {
        CtxBody(ctx, 200, { user, count })
    } else {
        CtxBody(ctx, 404, "")
    }
})

// 小程序后台添加管理员

router.post("/addAdminUser", async ctx => {
    let { username, password, id, status, name } = ctx.request.body 
    if (id) {
        let user = await AdminUser.findOneAndUpdate({ _id: id }, {
            $set: {
                username,
                password,
                status,
                name
            }
        }, { new: true })
        if (user) {
            CtxBody(ctx, 204, "")
        } else {
            CtxBody(ctx, 304, "")
        }
    } else {
        let users = new AdminUser({
            username,
            password,
            status,
            name
        })
        let res = await users.save()
        CtxBody(ctx, 202, "")
    }
})

// 管理员状态更改

router.post("/AdminStatusChange", async ctx => {
    let { id } = ctx.request.body 
    let self = ctx.state.user.id 
    if (id == self) {
        console.log(1);
        
        CtxBody(ctx, 30001, "")
    } else {
        console.log(2);
        let user = await AdminUser.findOne({ _id: id })
        if (user.status == 1) {
            console.log(3);
            let data = await AdminUser.findOneAndUpdate({ _id: id }, { $set: {
                status: "2"
            }}, { new: true })
            CtxBody(ctx, 204, "")
        } else {
            console.log(4);
            let data = await AdminUser.findOneAndUpdate({ _id: id }, { $set: {
                status: "1"
            }}, { new: true })
            CtxBody(ctx, 204, "")
        }
        
    }
})


// 小程序后台获取会员列表 role  会员身份

router.post("/getAllMember", async ctx => {
    let { role, page } = ctx.request.body 
    // console.log(role, page);
    
    let skipPage = page ? page : 1
    let PageSize = 10
    
    if (role) {
       // console.log(111);
        
        let user = await User.find({ role }).skip( (skipPage - 1) * PageSize).limit(PageSize)
        let allrole = await User.find({ role })
        let total = allrole.length
        if (user) {
            CtxBody(ctx, 200, {user, total})
        } else {
            CtxBody(ctx, 404, "")
        }
    } else {
        console.log(22);
        
        let user = await User.find().skip( (skipPage - 1) * PageSize).limit(PageSize)
        let total = await User.count()
        if (user) {
            CtxBody(ctx, 200, {user, total})
        } else {
            CtxBody(ctx, 404, "")
        }
    }
    
})

// 会员状态更改

router.post("/AdminStatusChange", async ctx => {
    let { id } = ctx.request.body 
    let self = ctx.state.user.id 
    if (id == self) {
        CtxBody(ctx, 30001, "")
    } else {
        let user = await User.findOne({ _id: id })
        if (user.status == 1) {
            let data = await User.findOneAndUpdate({ _id: id }, { $set: {
                status: "2"
            }}, { new: true })
            ctx.CtxBody(ctx, 204, "")
        } else {
            let data = await User.findOneAndUpdate({ _id: id }, { $set: {
                status: "1"
            }}, { new: true })
            ctx.CtxBody(ctx, 204, "")
        }
        
    }
})




module.exports = router